package com.example.demo.service;

import cn.hutool.core.util.ObjectUtil;
import com.example.demo.common.JwtTokenUtils;
import com.example.demo.dao.AdminDao;
import com.example.demo.dao.AuditDao;
import com.example.demo.dao.TypeDao;
import com.example.demo.entity.Admin;
import com.example.demo.entity.Audit;
import com.example.demo.entity.Params;
import com.example.demo.entity.Type;
import com.example.demo.exception.CustomException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class AuditService {

    @Resource
    private AuditDao auditDao;
    @Resource
    private AdminDao adminDao;

    public PageInfo<Audit> findBySearch(Params params) {
        Admin currentUser = JwtTokenUtils.getCurrentUser();
        if (ObjectUtil.isNull(currentUser)) {
            throw new CustomException("用户未登录重新登录");
        }
        if ("ROLE_USER".equals(currentUser.getRole())) {
            params.setUserId(currentUser.getId());
        }
        //开启分页查询
        PageHelper.startPage(params.getPageNum(), params.getPageSize());
        List<Audit> bySearch = auditDao.findBySearch(params);
        for (Audit audit : bySearch) {
            if (ObjectUtil.isNotEmpty(audit.getUserid())) {
                Admin user = adminDao.selectByPrimaryKey(audit.getUserid());
                if (ObjectUtil.isNotEmpty(user)) {
                    audit.setUserName(user.getName());
                }
            }
        }
        return PageInfo.of(bySearch);
    }

    public void add(Audit audit) {
        auditDao.insertSelective(audit);
    }

    public void update(Audit audit) {
        auditDao.updateByPrimaryKeySelective(audit);
    }

    public void delete(Integer id) {
        auditDao.deleteByPrimaryKey(id);
    }

    public List<Audit> findAll() {
        return auditDao.selectAll();
    }

}
